package com.hengtiansoft.lfy.chart.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.model.GroupRemoveListener;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.activity.Kdxf_VoiceDialogActivity;
import com.hengtiansoft.lfy.chart.adapter.ExpressionAdapter;
import com.hengtiansoft.lfy.chart.adapter.ExpressionPagerAdapter;
import com.hengtiansoft.lfy.chart.adapter.MessageAdapter;
import com.hengtiansoft.lfy.chart.adapter.MessageAdapter.MessageAdapterListener;
import com.hengtiansoft.lfy.chart.adapter.MiniPopupWindowAdapter;
import com.hengtiansoft.lfy.chart.adapter.VoicePlayClickListener;
import com.hengtiansoft.lfy.chart.chatpullrefresh.MMPullDownView;
import com.hengtiansoft.lfy.chart.chatpullrefresh.OnListViewBottomListener;
import com.hengtiansoft.lfy.chart.chatpullrefresh.OnListViewTopListener;
import com.hengtiansoft.lfy.chart.chatpullrefresh.OnRefreshAdapterDataListener;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.PopUtil;
import com.hengtiansoft.lfy.widget.AlertDialog;
import com.hengtiansoft.lfy.chart.domain.RobotUser;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.chart.utils.ImageUtils;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.hengtiansoft.lfy.chart.utils.SmileUtils;
import com.hengtiansoft.lfy.chart.utils.UserUtils;
import com.hengtiansoft.lfy.widget.MyPopupWindow;
import com.hengtiansoft.lfy.widget.ExpandGridView;
import com.hengtiansoft.lfy.widget.YesNoDialog;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMLocationMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMNormalFileMessageBody;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;
import com.hyphenate.util.VoiceRecorder;
import com.ztspeech.constant.ZTConstant;
import com.ztspeech.translator.ZTTranslator;
import com.ztspeech.translator.interf.ZTTranslatorListener;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * 聊天页面
 * 
 */
public class ChatActivity extends BaseActivity
        implements OnClickListener, EMMessageListener {
    private static final String TAG = "ChatActivity";
    private static final int REQUEST_CODE_EMPTY_HISTORY = 2;
    public static final int REQUEST_CODE_CONTEXT_MENU = 3;
    private static final int REQUEST_CODE_MAP = 4;
    public static final int REQUEST_CODE_TEXT = 5;
    public static final int REQUEST_CODE_VOICE = 6;
    public static final int REQUEST_CODE_PICTURE = 7;
    public static final int REQUEST_CODE_LOCATION = 8;
    public static final int REQUEST_CODE_NET_DISK = 9;
    public static final int REQUEST_CODE_FILE = 10;
    public static final int REQUEST_CODE_COPY_AND_PASTE = 11;
    public static final int REQUEST_CODE_PICK_VIDEO = 12;
    public static final int REQUEST_CODE_DOWNLOAD_VIDEO = 13;
    public static final int REQUEST_CODE_VIDEO = 14;
    public static final int REQUEST_CODE_DOWNLOAD_VOICE = 15;
    public static final int REQUEST_CODE_SELECT_USER_CARD = 16;
    public static final int REQUEST_CODE_SEND_USER_CARD = 17;
    public static final int REQUEST_CODE_CAMERA = 18;
    public static final int REQUEST_CODE_LOCAL = 19;
    public static final int REQUEST_CODE_CLICK_DESTORY_IMG = 20;
    public static final int REQUEST_CODE_GROUP_DETAIL = 21;
    public static final int REQUEST_CODE_SELECT_VIDEO = 23;
    public static final int REQUEST_CODE_SELECT_FILE = 24;
    public static final int REQUEST_CODE_ADD_TO_BLACKLIST = 25;

    public static final int RESULT_CODE_COPY = 1;
    public static final int RESULT_CODE_DELETE = 2;
    public static final int RESULT_CODE_FORWARD = 3;
    public static final int RESULT_CODE_OPEN = 4;
    public static final int RESULT_CODE_DWONLOAD = 5;
    public static final int RESULT_CODE_TO_CLOUD = 6;
    public static final int RESULT_CODE_EXIT_GROUP = 7;

    public static final int CHATTYPE_SINGLE = 1;
    public static final int CHATTYPE_GROUP = 2;
    public static final int CHATTYPE_CHATROOM = 3;

    public static final String COPY_IMAGE = "EASEMOBIMG";
    private View recordingContainer;
    private ImageView micImage;
    private TextView recordingHint;
    private ListView listView;

    private EditText mEditTextContent;
    private View buttonSetModeKeyboard;
    private View buttonSetModeVoice;
    private RelativeLayout mRlSend;
    private View buttonPressToSpeak;
    // private ViewPager expressionViewpager;
    private LinearLayout emojiIconContainer;
    private LinearLayout btnContainer;
    private ImageView locationImgview;
    private View more;
    private int position;
    private ClipboardManager clipboard;
    private ViewPager expressionViewpager;
    private InputMethodManager manager;
    private List<String> reslist;
    private int chatType;
    private EMConversation conversation;
    public static ChatActivity activityInstance = null;
    // 给谁发送消息
    private String toChatUsername;
    private VoiceRecorder voiceRecorder;
    private MessageAdapter adapter;
    private File cameraFile;
    public static int resendPos;

    private GroupListener groupListener;

    private ImageView iv_emoticons_normal;
    private ImageView iv_emoticons_checked;
    private RelativeLayout edittext_layout;
    private ProgressBar loadmorePB;
    private boolean isloading;
    private final int pagesize = 20;
    private boolean haveMoreData = true;

    public String playMsgId;

    public EMGroup group;
    public EMChatRoom room;
    public boolean isRobot;
    Context mContext;
    private String transferType = "chen";// 翻译类型：chen;ench
    private String textTask;// 翻译内容
    private RelativeLayout mRlUnSend;// 不可发送按钮
    private static final int TranslateReturn = 1111;
    // 翻译类型弹出框
    private MyPopupWindow mPopupWindow;
    private View mWindowView;
    private ListView mSelectList;

    private MiniPopupWindowAdapter mPwAdapter;
    private int mPosition = 0;
    private TextView mTvChangeLanguageFirst, mTvChangeLanguageSecond;
    private LinearLayout mLlChangeLanguageMini;
    private ProgressDialog mPd;
    private String voiceurl = null;
    private String voicefilename = null;
    private View listViewHeadView;
    private MMPullDownView mmPullDownView;

    private int dataCount = 40;
    private int refreshTime = 0;// 刷新的次数叠�?
    private boolean isVoice = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_chat);
        activityInstance = this;
        initView();
        setUpView();
    }

    /**
     * initView
     */
    protected void initView() {
        mPd = new ProgressDialog(mContext, ProgressDialog.THEME_HOLO_LIGHT);
        mPd.setCanceledOnTouchOutside(false);
        mPd.setMessage("正在翻译，请稍候...");
        // 上拉，下拉
        listView = (ListView) findViewById(R.id.list);
        listViewHeadView = getLayoutInflater()
                .inflate(R.layout.chatting_list_header, null);
        listView.addHeaderView(listViewHeadView);// 加了头部视图，就不会有跳跃感了，这是为什么?呢�
        listView.setOnScrollListener(mOnScrollListener);
        listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
        listView.setKeepScreenOn(true);
        listView.post(new Runnable() {

            @Override
            public void run() {
                listView.setSelection(listView.getCount());
            }
        });
        registerForContextMenu(listView);

        mmPullDownView = (MMPullDownView) findViewById(
                R.id.chatting_pull_down_view);
        mmPullDownView.setTopViewInitialize(true);
        mmPullDownView.setIsCloseTopAllowRefersh(false);
        mmPullDownView.setHasbottomViewWithoutscroll(false);
        mmPullDownView
                .setOnRefreshAdapterDataListener(mOnRefreshAdapterDataListener);
        mmPullDownView.setOnListViewTopListener(mOnListViewTopListener);
        mmPullDownView.setOnListViewBottomListener(mOnListViewBottomListener);
        mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
        buttonSetModeKeyboard = findViewById(R.id.btn_set_mode_keyboard);
        edittext_layout = (RelativeLayout) findViewById(R.id.edittext_layout);
        buttonSetModeVoice = findViewById(R.id.btn_set_mode_voice);
        mRlSend = (RelativeLayout) findViewById(R.id.rl_send);
        mRlSend.setOnClickListener(this);
        buttonPressToSpeak = findViewById(R.id.btn_press_to_speak);
        expressionViewpager = (ViewPager) findViewById(R.id.vPager);
        emojiIconContainer = (LinearLayout) findViewById(
                R.id.ll_face_container);
        btnContainer = (LinearLayout) findViewById(R.id.ll_btn_container);
        locationImgview = (ImageView) findViewById(R.id.btn_location);
        iv_emoticons_normal = (ImageView) findViewById(
                R.id.iv_emoticons_normal);
        iv_emoticons_checked = (ImageView) findViewById(
                R.id.iv_emoticons_checked);
        loadmorePB = (ProgressBar) findViewById(R.id.pb_load_more);
        mRlUnSend = (RelativeLayout) findViewById(R.id.rl_unsend);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        more = findViewById(R.id.more);
        voiceCallBtn = (ImageView) findViewById(R.id.btn_voice_call);
        videoCallBtn = (ImageView) findViewById(R.id.btn_video_call);
        mTvChangeLanguageFirst = (TextView) findViewById(
                R.id.tv_change_language_first);
        mTvChangeLanguageSecond = (TextView) findViewById(
                R.id.tv_change_language_second);
        mLlChangeLanguageMini = (LinearLayout) findViewById(
                R.id.ll_change_language_mini);
        if (Config.getposition() == 0) {
            transferType = "chen";
            mTvChangeLanguageFirst.setText("中文");
            mTvChangeLanguageSecond.setText("English");
        } else if (Config.getposition() == 1) {
            transferType = "ench";
            mTvChangeLanguageFirst.setText("English");
            mTvChangeLanguageSecond.setText("中文");
        } else {
            transferType = "chen";
            mTvChangeLanguageFirst.setText("中文");
            mTvChangeLanguageSecond.setText("English");
        }

        mLlChangeLanguageMini.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //showWindow(v);
                if("chen".equals(transferType)){
                    transferType="ench";
                    mTvChangeLanguageFirst.setText("English");
                    mTvChangeLanguageSecond.setText("中文");
                    //存储选择的翻译类型
                    Config.writeInterPreferencesPreference(1);
                }else{
                    transferType="chen";
                    mTvChangeLanguageFirst.setText("中文");
                    mTvChangeLanguageSecond.setText("English");
                    //存储选择的翻译类型
                    Config.writeInterPreferencesPreference(0);
                }
            }
        });

        // 表情list
        reslist = getExpressionRes(35);
        // 初始化表情viewpager
        List<View> views = new ArrayList<View>();
        View gv1 = getGridChildView(1);
        View gv2 = getGridChildView(2);
        views.add(gv1);
        views.add(gv2);
        expressionViewpager.setAdapter(new ExpressionPagerAdapter(views));
        // edittext_layout.requestFocus();
        // voiceRecorder = new VoiceRecorder(micImageHandler);
        // 点击说话时间
        // buttonPressToSpeak.setOnTouchListener(new PressToSpeakListen());
        buttonPressToSpeak.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (!CommonUtils.isFastDoubleClick()) {
                    if (CommonUtils.isNetWorkConnected(mContext)) {
                      /*  startActivityForResult(
                                new Intent(mContext, VoiceDialogActivity.class) //跳转到语音界面
                                .putExtra("transferType", transferType)
                                .putExtra("from", "chat")
                                .putExtra("toChatUsername",
                                        toChatUsername)
                                .putExtra("date",
                                        System.currentTimeMillis()),
                                TranslateReturn);*/
                        // TODO: 2017/1/16   Google_VoiceDialogActivity
                      //  if (!transferType.equals("ench")||!LfyApplication.getInstance().getGoogle()) {
                            startActivityForResult(
                                    new Intent(mContext,VoiceDialogActivity.class) //跳转到语音界面
                                            .putExtra("transferType", transferType)
                                            .putExtra("from", "chat")
                                            .putExtra("toChatUsername",
                                                    toChatUsername)
                                            .putExtra("date",
                                                    System.currentTimeMillis()),
                                    TranslateReturn);

                      //  }else {

                            /*startActivityForResult(
                                    new Intent(mContext, Google_VoiceDialogActivity.class) //跳转到语音界面
                                            .putExtra("transferType", transferType)
                                            .putExtra("from", "chat")
                                            .putExtra("toChatUsername",
                                                    toChatUsername)
                                            .putExtra("date",
                                                    System.currentTimeMillis()),
                                    TranslateReturn);*/
                     //   }

                    } else {
                        // 网络不可用，请检查网络
                        Toast.makeText(mContext,
                                getResources().getString(
                                        R.string.connect_failuer_toast),
                                Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        mEditTextContent.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) { //点击影藏表情控件
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE); //表情按钮变成未选中
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emojiIconContainer.setVisibility(View.GONE); //表情控件影藏
                btnContainer.setVisibility(View.GONE);//其他控件
            }
        });
        //监听完成
        mEditTextContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                    send();
                return false;
            }
        });
        // 监听文字框
        mEditTextContent.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (!TextUtils.isEmpty(s)) { //判断有没有输入来禁止和开启发送按钮
                    mRlUnSend.setVisibility(View.GONE);
                    mRlSend.setVisibility(View.VISIBLE);
                } else {
                    mRlUnSend.setVisibility(View.VISIBLE);
                    mRlSend.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 初始化弹窗 语言种类选择
        //initBox();
        //设置翻译服务器地址
        ZTTranslator.getTranslatorInstance().setServerAddr(Constants.TRANSLATE);
    }

    private OnListViewBottomListener mOnListViewBottomListener = new OnListViewBottomListener() {

        @Override
        public boolean getIsListViewToBottom() {
            if ((listView.getChildAt(-1 + listView.getChildCount())
                    .getBottom() > listView.getHeight())
                    || (listView.getLastVisiblePosition() != -1
                            + listView.getAdapter().getCount())) {

                return false;
            } else {

                return true;
            }
        }
    };
    private OnListViewTopListener mOnListViewTopListener = new OnListViewTopListener() {

        @Override
        public boolean getIsListViewToTop() {
            View topListView = listView
                    .getChildAt(listView.getFirstVisiblePosition());
            if ((topListView == null) || (topListView.getTop() != 0)) {
                return false;
            } else {
                return true;
            }
        }
    };

    private OnRefreshAdapterDataListener mOnRefreshAdapterDataListener = new OnRefreshAdapterDataListener() {

        @Override
        public void refreshData() {
            Log.e(TAG, "refreshData()*************");
            listView.setSelectionFromTop(1, mmPullDownView.getTopViewHeight());

        }

    };
    private OnScrollListener mOnScrollListener = new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                View topView = listView
                        .getChildAt(listView.getFirstVisiblePosition());
                if ((topView != null) && (topView.getTop() == 0)) {
                    mmPullDownView.startTopScroll();
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            if (mmPullDownView != null) {
                if (listView.getCount() < dataCount) {
                    mmPullDownView.setIsCloseTopAllowRefersh(false);
                } else {
                    mmPullDownView.setIsCloseTopAllowRefersh(true);
                }
            }
        }
    };

    private void setUpView() {
        iv_emoticons_normal.setOnClickListener(this); //图片点击事件
        iv_emoticons_checked.setOnClickListener(this);
        // position = getIntent().getIntExtra("position", -1);
        clipboard = (ClipboardManager) getSystemService(
                Context.CLIPBOARD_SERVICE);
        manager = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//隐藏软键盘
        wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))//防止CPU休眠
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        // 判断单聊还是群聊
        chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

        if (chatType == CHATTYPE_SINGLE) { // 单聊
            findViewById(R.id.container_to_group).setVisibility(View.GONE);
            findViewById(R.id.container_to_one).setVisibility(View.VISIBLE);
            toChatUsername = getIntent().getStringExtra("userId").toLowerCase(); //用户名
            Map<String, RobotUser> robotMap = ((DemoHXSDKHelper) HXSDKHelper
                    .getInstance()).getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
                String nick = robotMap.get(toChatUsername).getNick();
                if (!TextUtils.isEmpty(nick)) {
                    ((TextView) findViewById(R.id.name)).setText(nick);
                } else {
                    ((TextView) findViewById(R.id.name))
                            .setText(toChatUsername);
                }
            } else {
                UserUtils.setUserNick(toChatUsername,
                        (TextView) findViewById(R.id.name));
            }
        } else {
            // 群聊
            findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
            findViewById(R.id.container_to_one).setVisibility(View.GONE);
            findViewById(R.id.ll_change_language_mini)
                    .setVisibility(View.VISIBLE);
            findViewById(R.id.container_voice_call).setVisibility(View.GONE);
            findViewById(R.id.container_video_call).setVisibility(View.GONE);
            toChatUsername = getIntent().getStringExtra("groupId");

            if (chatType == CHATTYPE_GROUP) {
                onGroupViewCreation(); //获取房间名和监听群被解散事件
            } else {
                onChatRoomViewCreation(); //群组
            }
        }

        // for chatroom type, we only init conversation and create view adapter
        // on success 转发消息
        if (chatType != CHATTYPE_CHATROOM) { //不是群组
            onConversationInit();//加载db
            onListViewCreation();//显示界面监听播放音频事件 语音合成播放
            // show forward message if the message is not null
            String forward_msg_id = getIntent()
                    .getStringExtra("forward_msg_id");
            String forward_msg_content = getIntent()
                    .getStringExtra("forward_msg_content");
            String translate = getIntent().getStringExtra("translate");
            Log.i(TAG, forward_msg_id + "--" + forward_msg_content + "--"
                    + translate);
            if (forward_msg_id != null) {
                // 显示发送要转发的消息
                forwardMessage(forward_msg_id);
            } else if (forward_msg_content != null && translate != null) {
                sendText(forward_msg_content, translate); //发送消息
            }
        }
    }

    protected void onConversationInit() {
        if (chatType == CHATTYPE_SINGLE) {
            conversation = EMClient.getInstance().chatManager().getConversation(
                    toChatUsername, EMConversation.EMConversationType.Chat,true);//, EMConversation.EMConversationType.Chat
        } else if (chatType == CHATTYPE_GROUP) {
            conversation =  EMClient.getInstance().chatManager().getConversation(
                    toChatUsername, EMConversation.EMConversationType.GroupChat,true);
        } else if (chatType == CHATTYPE_CHATROOM) {
            conversation =  EMClient.getInstance().chatManager().getConversation(
                    toChatUsername, EMConversation.EMConversationType.ChatRoom,true);
        }

        // 把此会话的未读数置为0
        conversation.markAllMessagesAsRead();

        // 初始化db时，每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded
        // 这个数目如果比用户期望进入会话界面时显示的个数不一样，就多加载一些
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
          //  if (chatType == CHATTYPE_SINGLE) {
                conversation.loadMoreMsgFromDB(msgId, pagesize);
           // } else {
          //      conversation.loadMoreGroupMsgFromDB(msgId, pagesize);
          //  }
        }

        EMClient.getInstance().chatroomManager()
                .addChatRoomChangeListener(new EMChatRoomChangeListener() {

                    @Override
                    public void onChatRoomDestroyed(String roomId,
                                                    String roomName) {
                        if (roomId.equals(toChatUsername)) {
                            finish();
                        }
                    }

                    @Override
                    public void onMemberJoined(String roomId,
                                               String participant) {
                    }

                    @Override
                    public void onMemberExited(String roomId, String roomName,
                                               String participant) {

                    }

                    @Override
                    public void onRemovedFromChatRoom(String roomId, String roomName,
                                               String participant) {
                        if (roomId.equals(toChatUsername)) {
                            String curUser = EMClient.getInstance()
                                    .getCurrentUser();
                            if (curUser.equals(participant)) {
                                EMClient.getInstance().chatroomManager()
                                        .leaveChatRoom(toChatUsername);
                                finish();
                            }
                        }
                    }

                });
    }
    //
    protected void onListViewCreation() {
        adapter = new MessageAdapter(ChatActivity.this, toChatUsername,
                chatType);
        // 显示消息
        listView.setAdapter(adapter);

        listView.setOnScrollListener(new ListScrollListener());
        adapter.refreshSelectLast();
        adapter.setAdapterListener(new MessageAdapterListener() {

            @Override
            public void onPlayer(int position) {
                // TODO Auto-generated method stub
                // Toast.makeText(mContext, "播放事件", Toast.LENGTH_LONG).show();
                if (CommonUtils.isNetWorkConnected(mContext)) { //点击喇叭图标播放
                    EMMessage message = adapter.getItem(position);
                    String synText = "Invite you to join group chat!";
                    try {
                        synText = message.getStringAttribute("translate");
                    } catch (HyphenateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (synText.length() <= 0)
                        return;
                    //TTSPlayer.getInstense().TTSPlay(synText);
                    Kdxf_TTSPlayer.getInstense().TTSPlay(synText,transferType,"");
                } else {
                    Toast.makeText(mContext, "请检查网络！", Toast.LENGTH_LONG)
                            .show();
                }
            }
        });
        adapter.setClickListener(new PopUtil.MyClickListener() {
            @Override
            public void copy(int pos, View v) {
                EMMessage copyMsg = ((EMMessage) adapter
                        .getItem(pos));
                // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                clipboard.setText(
                        ((EMTextMessageBody) copyMsg.getBody()).getMessage());
                Toast.makeText(ChatActivity.this, getString(R.string.copied), Toast.LENGTH_LONG)
                        .show();
            }

            @Override
            public void delete(final int pos, View v) {
                new YesNoDialog.Builder(ChatActivity.this)
                        .setMessage(getString(R.string.delete_title_one))
                        .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                EMMessage deleteMsg = (EMMessage) adapter
                                        .getItem(pos);
                                conversation.removeMessage(deleteMsg.getMsgId());
                                adapter.refreshSeekTo(pos);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create().show();


            }

            @Override
            public void collection(int pos, View v) {
                EMMessage forwardMsg = (EMMessage) adapter
                        .getItem(pos);
                Log.i(TAG, forwardMsg.toString());
                Intent intent = new Intent(ChatActivity.this, ForwardMessageActivity.class);
                intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
                startActivity(intent);
            }
        });
        listView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                more.setVisibility(View.GONE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
                emojiIconContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.GONE);
                return false;
            }
        });
    }

    protected void onGroupViewCreation() {
        group = EMClient.getInstance().groupManager().getGroup(toChatUsername);//获取房间名

        if (group != null) {
            ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
        } else {
            ((TextView) findViewById(R.id.name)).setText(toChatUsername);
        }

        // 监听当前会话的群聊解散被T事件
        groupListener = new GroupListener();
        EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);
    }

    protected void onChatRoomViewCreation() {
        findViewById(R.id.container_to_group).setVisibility(View.GONE);
        findViewById(R.id.container_to_one).setVisibility(View.VISIBLE);
        final ProgressDialog pd = ProgressDialog.show(this, "",
                "Joining......");
        EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, //进入房间
                new EMValueCallBack<EMChatRoom>() {

                    @Override
                    public void onSuccess(EMChatRoom value) {
                        // TODO Auto-generated method stub
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pd.dismiss();
                                room =EMClient.getInstance().chatroomManager()
                                        .getChatRoom(toChatUsername); //获取房间名
                                if (room != null) {
                                    ((TextView) findViewById(R.id.name))
                                            .setText(room.getName());
                                } else {
                                    ((TextView) findViewById(R.id.name))
                                            .setText(toChatUsername);
                                }
                                EMLog.d(TAG, "join room success : "
                                        + room.getName());

                                onConversationInit();

                                onListViewCreation();
                            }
                        });
                    }

                    @Override
                    public void onError(final int error, String errorMsg) {
                        // TODO Auto-generated method stub
                        EMLog.d(TAG, "join room failure : " + error);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pd.dismiss();
                            }
                        });
                        finish();
                    }
                });
    }

    /**
     * onActivityResult
     */
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case TranslateReturn:
                String res = data.getStringExtra("result");
                if (res != null && !res.equals("")) {
                    if (res.equals(Constants.No_RESULT)) {
                        if("ench".equals(transferType)){
                            Toast.makeText(this, getString(R.string.say_againe),
                                    Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(this, getString(R.string.say_again),
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else if (res.equals(Constants.ZR_ERROR)) {
                        Toast.makeText(mContext, "网络识别出错", Toast.LENGTH_SHORT)
                                .show();
                    } else if (res.equals(Constants.ZR_STOP_NULL)) {
                        return;
                    } else {
                        mPd.show();
//                        String url = data.getStringExtra("url");
//                        String fileName = data.getStringExtra("fileName");
//                        VoiceTranslateTask voiceTranslateTask = new VoiceTranslateTask();
//                        voiceTranslateTask.execute(res, url, fileName);
                        voiceurl = data.getStringExtra("url");
                        voicefilename = data.getStringExtra("fileName");
                        isVoice = true;
                        textTask=res;
                        if("chen".equals(transferType)){
                            ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_CHEN);
                        }else{
                            ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
                        }

                        ZTTranslator.getTranslatorInstance().translate(mTranLisenter,res);
                    }
                } else {
                    Toast.makeText(mContext, "网络识别出错!", Toast.LENGTH_SHORT)
                            .show();
                }
                break;

            default:
                break;
            }
        }

        if (resultCode == RESULT_CODE_EXIT_GROUP) {
            setResult(RESULT_OK);
            finish();
            return;
        }
        if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
            switch (resultCode) {
            case RESULT_CODE_COPY: // 复制消息
                EMMessage copyMsg = ((EMMessage) adapter
                        .getItem(data.getIntExtra("position", -1)));
                // clipboard.setText(SmileUtils.getSmiledText(ChatActivity.this,
                // ((TextMessageBody) copyMsg.getBody()).getMessage()));
                clipboard.setText(
                        ((EMTextMessageBody) copyMsg.getBody()).getMessage());
                break;
            case RESULT_CODE_DELETE: // 删除消息
                EMMessage deleteMsg = (EMMessage) adapter
                        .getItem(data.getIntExtra("position", -1));
                conversation.removeMessage(deleteMsg.getMsgId());
                adapter.refreshSeekTo(
                        data.getIntExtra("position", adapter.getCount()) - 1);
                break;

            case RESULT_CODE_FORWARD: // 转发消息
                EMMessage forwardMsg = (EMMessage) adapter
                        .getItem(data.getIntExtra("position", 0));
                Log.i(TAG, forwardMsg.toString());
                Intent intent = new Intent(this, ForwardMessageActivity.class);
                intent.putExtra("forward_msg_id", forwardMsg.getMsgId());
                startActivity(intent);
                break;

            default:
                break;
            }
        }
        if (resultCode == RESULT_OK) { // 清空消息
            if (requestCode == REQUEST_CODE_EMPTY_HISTORY) {
                // 清空会话
                EMClient.getInstance().chatManager().deleteConversation(toChatUsername,true);
                adapter.refresh();
            } else if (requestCode == REQUEST_CODE_CAMERA) { // 发送照片
            } else if (requestCode == REQUEST_CODE_SELECT_VIDEO) { // 发送本地选择的视频
            } else if (requestCode == REQUEST_CODE_LOCAL) { // 发送本地图片
            } else if (requestCode == REQUEST_CODE_SELECT_FILE) { // 发送选择的文件
            } else if (requestCode == REQUEST_CODE_MAP) { // 地图
                // 重发消息
            } else if (requestCode == REQUEST_CODE_TEXT
                    || requestCode == REQUEST_CODE_VOICE
                    || requestCode == REQUEST_CODE_PICTURE
                    || requestCode == REQUEST_CODE_LOCATION
                    || requestCode == REQUEST_CODE_VIDEO
                    || requestCode == REQUEST_CODE_FILE) {
                resendMessage((EMMessage)data.getParcelableExtra("msgId"));
            } else if (requestCode == REQUEST_CODE_COPY_AND_PASTE) {
                // 粘贴
                if (!TextUtils.isEmpty(clipboard.getText())) {
                    String pasteText = clipboard.getText().toString();
                    if (pasteText.startsWith(COPY_IMAGE)) {
                        // 把图片前缀去掉，还原成正常的path
                        sendPicture(pasteText.replace(COPY_IMAGE, ""));
                    }

                }
            } else if (requestCode == REQUEST_CODE_ADD_TO_BLACKLIST) { // 移入黑名单
                EMMessage deleteMsg = (EMMessage) adapter
                        .getItem(data.getIntExtra("position", -1));
                addUserToBlacklist(deleteMsg.getFrom());
            } else if (conversation.getAllMessages().size() > 0) {
                adapter.refresh();
                setResult(RESULT_OK);
            } else if (requestCode == REQUEST_CODE_GROUP_DETAIL) {
                adapter.refresh();
            }

        }
    }

    /**
     * 消息图标点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        String st1 = getResources().getString(R.string.not_connect_to_server);
        int id = view.getId();
        if (id == R.id.rl_send) {// 点击发送按钮(发文字和表情)
            send();
        } else if (id == R.id.btn_take_picture) {
            selectPicFromCamera();// 点击照相图标
        } else if (id == R.id.btn_picture) {
            selectPicFromLocal(); // 点击图片图标
        } else if (id == R.id.btn_location) { // 位置
        } else if (id == R.id.iv_emoticons_normal) { // 点击显示表情框
            more.setVisibility(View.VISIBLE);
            iv_emoticons_normal.setVisibility(View.INVISIBLE);
            iv_emoticons_checked.setVisibility(View.VISIBLE);
            btnContainer.setVisibility(View.GONE);
            emojiIconContainer.setVisibility(View.VISIBLE);
            hideKeyboard();
        } else if (id == R.id.iv_emoticons_checked) { // 点击隐藏表情框
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            btnContainer.setVisibility(View.VISIBLE);
            emojiIconContainer.setVisibility(View.GONE);
            more.setVisibility(View.GONE);

        } else if (id == R.id.btn_video) {// 点击摄像图标
        } else if (id == R.id.btn_file) { // 点击文件图标
            selectFileFromLocal();
        } else if (id == R.id.btn_voice_call) { // 点击语音电话图标

        } else if (id == R.id.btn_video_call) { // 视频通话

        }
    }

    private void send() {
        String s = mEditTextContent.getText().toString();
        if (!s.equals(null) & !s.equals("")) {
            textTask=s;
           s= s.replaceAll("\\[.+\\]","");
            mEditTextContent.setText("");
            isVoice = false;
            if(TextUtils.isEmpty(s)){
                sendText(textTask, s);
                return;
            }
            mPd.show();
            if("chen".equals(transferType)){
                ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_CHEN);
            }else{
                ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
            }
            ZTTranslator.getTranslatorInstance().translate(mTranLisenter,s);
        }
    }

    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        for(EMMessage message:messages) {
            //收到消息
            String username = null;
            // 群组消息
            if (message.getChatType() == EMMessage.ChatType.GroupChat
                    || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();

            } else {
                // 单聊消息
                username = message.getFrom();
            }

            // 如果是当前会话的消息，刷新聊天页面
            if (username.equals(getToChatUsername())) {
                //是否自动播放 true自动播放
                if (Config.getSettingAutoPlayer()) {
                    try {
                       /* TTSPlayer.getInstense().TTSPlay(
                                message.getStringAttribute("translate"));*/
                        Kdxf_TTSPlayer.getInstense().TTSPlay(message.getStringAttribute("translate"), transferType, "");
                    } catch (HyphenateException e) {
                    }
                }
                refreshUIWithNewMessage();//刷新数据和选择最后一行
                // 声音和震动提示有新消息
                HXSDKHelper.getInstance().getNotifier()
                        .viberateAndPlayTone(message);
            } else {
                // 如果消息不是和当前聊天ID的消息
                HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) { //收到透传消息

    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        refreshUI(); //刷新数据
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        refreshUI(); //刷新数据
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {
       // Log.i("supeng",change+"change");
    }


    private void refreshUIWithNewMessage() {
        if (adapter == null) {
            return;
        }

        runOnUiThread(new Runnable() {
            public void run() {
                adapter.refreshSelectLast();
            }
        });
    }

    private void refreshUI() {
        if (adapter == null) {
            return;
        }

        runOnUiThread(new Runnable() {
            public void run() {
                adapter.refresh();
            }
        });
    }

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtils.isExitsSdcard()) {
            String st = getResources()
                    .getString(R.string.sd_card_does_not_exist);
            Toast.makeText(getApplicationContext(), st, Toast.LENGTH_SHORT).show();
            return;
        }

        cameraFile = new File(PathUtil.getInstance().getImagePath(),
                Config.getUserName()
                        + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
                        MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                REQUEST_CODE_CAMERA);
    }

    /**
     * 选择文件
     */
    private void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_LOCAL);
    }

    /**
     * 发送文本消息
     *
     * @param content
     *            原信息文本
     * @param translate
     *            翻译后信息文本
     */
    public void sendText(String content, String translate) {

        if (content.length() > 0) {
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            } else if (chatType == CHATTYPE_CHATROOM) {
                message.setChatType(EMMessage.ChatType.ChatRoom);
            }
            if (isRobot) {
                message.setAttribute("em_robot_message", true);
            }
            EMTextMessageBody txtBody = new EMTextMessageBody(content);
            // 设置消息body
            message.addBody(txtBody);
            // 设置翻译消息置扩展属性
            message.setAttribute("translate", translate);
            // 设置要发给谁,用户username或者群聊groupid
            message.setTo(toChatUsername);
            // 把messgage加到conversation中
            //conversation.addMessage(message);
            EMClient.getInstance().chatManager().sendMessage(message);
            Log.i("supeng", "sendMessage");
            // 通知adapter有消息变动，adapter会根据加入的这条message显示消息和调用sdk的发送方法
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    adapter.refreshSelectLast();
                }
            }).start();

            setResult(RESULT_OK);

        }
    }

    /**
     * 发送语音
     *
     * @param filePath
     * @param fileName
     * @param length
     * @param isResend
     */
    private void sendVoice(String filePath, String fileName, String length,
                           boolean isResend, String content, String translate) {
        Log.i(TAG, fileName);
        if (!(new File(filePath).exists())) {
            return;
        }
        try {
            final EMMessage message = EMMessage
                    .createSendMessage(EMMessage.Type.VOICE);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            } else if (chatType == CHATTYPE_CHATROOM) {
                message.setChatType(EMMessage.ChatType.ChatRoom);
            }
            message.setTo(toChatUsername);//发送给谁
            int len = Integer.parseInt(length);
            EMVoiceMessageBody body = new EMVoiceMessageBody(new File(filePath),
                    len);
            message.addBody(body);
            if (isRobot) {
                message.setAttribute("em_robot_message", true);
            }
            message.setAttribute("content", content);
            message.setAttribute("translate", translate);
            //conversation.addMessage(message);
            EMClient.getInstance().chatManager().sendMessage(message);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(200);
                        adapter.refreshSelectLast();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            setResult(RESULT_OK);
            // send file
            // sendVoiceSub(filePath, fileName, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送图片
     *
     * @param filePath
     */
    private void sendPicture(final String filePath) {
        String to = toChatUsername;
        // create and add image message in view
        final EMMessage message = EMMessage
                .createSendMessage(EMMessage.Type.IMAGE);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }

        message.setTo(to);
        EMImageMessageBody body = new EMImageMessageBody(new File(filePath));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        message.addBody(body);
        if (isRobot) {
            message.setAttribute("em_robot_message", true);
        }
        //conversation.addMessage(message);
        EMClient.getInstance().chatManager().sendMessage(message);
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);
        // more(more);
    }

    /**
     * 发送视频消息
     */
    private void sendVideo(final String filePath, final String thumbPath,
                           final int length) {
        final File videoFile = new File(filePath);
        if (!videoFile.exists()) {
            return;
        }
        try {
            EMMessage message = EMMessage.createVideoSendMessage(filePath, thumbPath, (int) videoFile.length(), toChatUsername);
            // 如果是群聊，设置chattype,默认是单聊
            if (chatType == CHATTYPE_GROUP) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            } else if (chatType == CHATTYPE_CHATROOM) {
                message.setChatType(EMMessage.ChatType.ChatRoom);
            }
            if (isRobot) {
                message.setAttribute("em_robot_message", true);
            }
            EMClient.getInstance().chatManager().sendMessage(message);
            listView.setAdapter(adapter);
            adapter.refreshSelectLast();
            setResult(RESULT_OK);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param selectedImage
     */
    private void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        String st8 = getResources().getString(R.string.cant_find_pictures);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;

            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendPicture(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(this, st8, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;

            }
            sendPicture(file.getAbsolutePath());
        }

    }

    /**
     * 发送位置信息
     *
     * @param latitude
     * @param longitude
     * @param imagePath
     * @param locationAddress
     */
    private void sendLocationMsg(double latitude, double longitude,
                                 String imagePath, String locationAddress) {
        EMMessage message = EMMessage
                .createSendMessage(EMMessage.Type.LOCATION);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }
        EMLocationMessageBody locBody = new EMLocationMessageBody(locationAddress,
                latitude, longitude);
        message.addBody(locBody);
        message.setTo(toChatUsername);
        if (isRobot) {
            message.setAttribute("em_robot_message", true);
        }
       // conversation.addMessage(message);
        EMClient.getInstance().chatManager().sendMessage(message);
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);

    }

    /**
     * 发送文件
     *
     * @param uri
     */
    private void sendFile(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = { "_data" };
            Cursor cursor = null;

            try {
                cursor = getContentResolver().query(uri, projection, null, null,
                        null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            String st7 = getResources().getString(R.string.File_does_not_exist);
            Toast.makeText(getApplicationContext(), st7, Toast.LENGTH_SHORT).show();
            return;
        }
        if (file.length() > 10 * 1024 * 1024) {
            String st6 = getResources()
                    .getString(R.string.The_file_is_not_greater_than_10_m);
            Toast.makeText(getApplicationContext(), st6, Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建一个文件消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
        // 如果是群聊，设置chattype,默认是单聊
        if (chatType == CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        } else if (chatType == CHATTYPE_CHATROOM) {
            message.setChatType(EMMessage.ChatType.ChatRoom);
        }

        message.setTo(toChatUsername);
        // add message body
        EMNormalFileMessageBody body = new EMNormalFileMessageBody(
                new File(filePath));
        message.addBody(body);
        if (isRobot) {
            message.setAttribute("em_robot_message", true);
        }
        //conversation.addMessage(message);
        EMClient.getInstance().chatManager().sendMessage(message);
        listView.setAdapter(adapter);
        adapter.refreshSelectLast();
        setResult(RESULT_OK);
    }

    /**
     * 重发消息
     */
    private void resendMessage(EMMessage msg) {
//        EMMessage msg = null;
//        msg = conversation.getMessage(resendPos);
        // msg.setBackSend(true);
        msg.setStatus(EMMessage.Status.CREATE);
        EMClient.getInstance().chatManager().sendMessage(msg);
        adapter.refreshSeekTo(resendPos);
    }

    /**
     * 显示语音图标按钮
     *
     * @param view
     */
    public void setModeVoice(View view) {
        hideKeyboard();
        edittext_layout.setVisibility(View.GONE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeKeyboard.setVisibility(View.VISIBLE);
        mRlSend.setVisibility(View.GONE);
        buttonPressToSpeak.setVisibility(View.VISIBLE);
        iv_emoticons_normal.setVisibility(View.VISIBLE);
        iv_emoticons_checked.setVisibility(View.INVISIBLE);
        btnContainer.setVisibility(View.VISIBLE);
        emojiIconContainer.setVisibility(View.GONE);
        mRlUnSend.setVisibility(View.GONE);
    }

    /**
     * 显示键盘图标
     *
     * @param view
     */
    public void setModeKeyboard(View view) {
        edittext_layout.setVisibility(View.VISIBLE);
        more.setVisibility(View.GONE);
        view.setVisibility(View.GONE);
        buttonSetModeVoice.setVisibility(View.VISIBLE);
        mEditTextContent.requestFocus();
        buttonPressToSpeak.setVisibility(View.GONE);
        if (TextUtils.isEmpty(mEditTextContent.getText())) {
            mRlSend.setVisibility(View.GONE);
            mRlUnSend.setVisibility(View.VISIBLE);
        } else {
            mRlSend.setVisibility(View.GONE);
        }

    }

    /**
     * 点击清空聊天记录
     *
     * @param view
     */
    public void emptyHistory(View view) {
        String st5 = getResources()
                .getString(R.string.Whether_to_empty_all_chats);
        startActivityForResult(new Intent(this, AlertDialog.class)
                .putExtra("titleIsCancel", true).putExtra("msg", st5)
                .putExtra("cancel", true), REQUEST_CODE_EMPTY_HISTORY);
    }

    /**
     * 点击进入群组详情
     *
     * @param view
     */
    public void toGroupDetails(View view) {
        if (room == null && group == null) {
            Toast.makeText(getApplicationContext(), R.string.gorup_not_found, Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        if (chatType == CHATTYPE_GROUP) { //群组详细
            startActivityForResult(
                    (new Intent(this, GroupDetailsActivity.class)
                            .putExtra("groupId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        } else {   //?
            startActivityForResult(
                    (new Intent(this, ChatRoomDetailsActivity.class)
                            .putExtra("roomId", toChatUsername)),
                    REQUEST_CODE_GROUP_DETAIL);
        }
    }

    /**
     * 点击进入个人详情
     *
     * @param view
     */
    public void toDetails(View view) {
        Intent intent = new Intent();
        intent.setClass(mContext, PersonalDetailsActivity.class);
        intent.putExtra("username", toChatUsername);
        intent.putExtra("type", "send");
        startActivity(intent);
    }

    /**
     * 显示或隐藏图标按钮页
     *
     * @param view
     */
    public void toggleMore(View view) {
        if (more.getVisibility() == View.GONE) {
            EMLog.d(TAG, "more gone");
            hideKeyboard();
            more.setVisibility(View.VISIBLE);
            btnContainer.setVisibility(View.VISIBLE);
            emojiIconContainer.setVisibility(View.GONE);
        } else {
            if (emojiIconContainer.getVisibility() == View.VISIBLE) {
                emojiIconContainer.setVisibility(View.GONE);
                btnContainer.setVisibility(View.VISIBLE);
                iv_emoticons_normal.setVisibility(View.VISIBLE);
                iv_emoticons_checked.setVisibility(View.INVISIBLE);
            } else {
                more.setVisibility(View.GONE);
            }

        }

    }

    /**
     * 点击文字输入框
     *
     * @param v
     */
    public void editClick(View v) {
        listView.setSelection(listView.getCount() - 1);
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
        }

    }

    private PowerManager.WakeLock wakeLock;
    private ImageView voiceCallBtn;
    private ImageView videoCallBtn;


    /**
     * 按住说话listener  废弃
     *
     */
   class PressToSpeakListen implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!CommonUtils.isExitsSdcard()) {
                    String st4 = getResources()
                            .getString(R.string.Send_voice_need_sdcard_support);
                    Toast.makeText(ChatActivity.this, st4, Toast.LENGTH_SHORT)
                            .show();
                    return false;
                }
                try {
                    v.setPressed(true);
                    wakeLock.acquire();//开启CPU不休眠
                    if (VoicePlayClickListener.isPlaying)
                        VoicePlayClickListener.currentPlayListener
                                .stopPlayVoice();
                    recordingContainer.setVisibility(View.VISIBLE);
                    recordingHint
                            .setText(getString(R.string.move_up_to_cancel));
                    recordingHint.setBackgroundColor(Color.TRANSPARENT);
                    voiceRecorder.startRecording(null, toChatUsername,
                            getApplicationContext());
                } catch (Exception e) {
                    e.printStackTrace();
                    v.setPressed(false);
                    if (wakeLock.isHeld())
                        wakeLock.release();
                    if (voiceRecorder != null)
                        voiceRecorder.discardRecording();
                    recordingContainer.setVisibility(View.INVISIBLE);
                    Toast.makeText(ChatActivity.this, R.string.recoding_fail,
                            Toast.LENGTH_SHORT).show();
                    return false;
                }

                return true;
            case MotionEvent.ACTION_MOVE: {
                if (event.getY() < 0) {
                    recordingHint
                            .setText(getString(R.string.release_to_cancel));
                    recordingHint.setBackgroundResource(
                            R.drawable.recording_text_hint_bg);
                } else {
                    recordingHint
                            .setText(getString(R.string.move_up_to_cancel));
                    recordingHint.setBackgroundColor(Color.TRANSPARENT);
                }
                return true;
            }
            case MotionEvent.ACTION_UP:
                v.setPressed(false);
                recordingContainer.setVisibility(View.INVISIBLE);
                if (wakeLock.isHeld())
                    wakeLock.release();
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    voiceRecorder.discardRecording();

                } else {
                    // stop recording and send voice file
                    String st1 = getResources()
                            .getString(R.string.Recording_without_permission);
                    String st2 = getResources().getString(
                            R.string.The_recording_time_is_too_short);
                    String st3 = getResources()
                            .getString(R.string.send_failure_please);
                    try {
                        int length = voiceRecorder.stopRecoding();
                        if (length > 0) {
                            sendVoice(voiceRecorder.getVoiceFilePath(),
                                    voiceRecorder
                                            .getVoiceFileName(toChatUsername),
                                    Integer.toString(length), false, null,
                                    null);
                        } else if (length == EMError.FILE_INVALID ) {
                            Toast.makeText(getApplicationContext(), st1,
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), st2,
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(ChatActivity.this, st3,
                                Toast.LENGTH_SHORT).show();
                    }

                }
                return true;
            default:
                recordingContainer.setVisibility(View.INVISIBLE);
                if (voiceRecorder != null)
                    voiceRecorder.discardRecording();
                return false;
            }
        }
    }

    /**
     * 获取表情的gridview的子view
     * 
     * @param i
     * @return
     */
    private View getGridChildView(int i) {
        View view = View.inflate(this, R.layout.expression_gridview, null);
        ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
        List<String> list = new ArrayList<String>();
        if (i == 1) {
            List<String> list1 = reslist.subList(0, 20);
            list.addAll(list1);
        } else if (i == 2) {
            list.addAll(reslist.subList(20, reslist.size()));
        }
        list.add("delete_expression");
        final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this,
                1, list);
        gv.setAdapter(expressionAdapter);
        gv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String filename = expressionAdapter.getItem(position);
                try {
                    // 文字输入框可见时，才可输入表情
                    // 按住说话可见，不让输入表情
                    if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                        if (filename != "delete_expression") { // 不是删除键，显示表情
                            // 这里用的反射，所以混淆的时候不要混淆SmileUtils这个类
                            Class clz = Class.forName(
                                    "com.hengtiansoft.lfy.chart.utils.SmileUtils");
                            Field field = clz.getField(filename);
                            mEditTextContent.append(
                                    SmileUtils.getSmiledText(ChatActivity.this,
                                            (String) field.get(null))); //添加表情
                        } else { // 删除文字或者表情
                            if (!TextUtils
                                    .isEmpty(mEditTextContent.getText())) {

                                int selectionStart = mEditTextContent
                                        .getSelectionStart();// 获取光标的位置
                                if (selectionStart > 0) {
                                    String body = mEditTextContent.getText()
                                            .toString();
                                    String tempStr = body.substring(0,
                                            selectionStart);
                                    int i = tempStr.lastIndexOf("[");// 获取最后一个表情的位置
                                    if (i != -1) {
                                        CharSequence cs = tempStr.substring(i,
                                                selectionStart);
                                        if (SmileUtils
                                                .containsKey(cs.toString())) //是否是表情
                                            mEditTextContent.getEditableText() //删除表情
                                                    .delete(i, selectionStart);
                                        else
                                            mEditTextContent.getEditableText() //删除文本 文本是一个字
                                                    .delete(selectionStart - 1,
                                                            selectionStart);
                                    } else {
                                        mEditTextContent.getEditableText() //删除文本 文本是一个字
                                                .delete(selectionStart - 1,
                                                        selectionStart);
                                    }
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                }

            }
        });
        return view;
    }

    public List<String> getExpressionRes(int getSum) {
        List<String> reslist = new ArrayList<String>();
        for (int x = 1; x <= getSum; x++) {
            String filename = "ee_" + x;

            reslist.add(filename);

        }
        return reslist;

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
        if (groupListener != null) {
            EMClient.getInstance().groupManager()
                    .removeGroupChangeListener(groupListener);
        }
        //TTSPlayer.getInstense().stop();
        Kdxf_TTSPlayer.getInstense().stop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (group != null)
            ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
        voiceCallBtn.setEnabled(true);
        videoCallBtn.setEnabled(true);

        if (adapter != null) {
            adapter.refresh();
        }

        DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
                .getInstance();
        sdkHelper.pushActivity(this); //前台
        // register the event listener when enter the foreground 监听发送事件
//        EMChatManager.getInstance().registerEventListener(this,
//                new EMNotifierEvent.Event[] {
//                        EMNotifierEvent.Event.EventNewMessage,
//                        EMNotifierEvent.Event.EventOfflineMessage,
//                        EMNotifierEvent.Event.EventDeliveryAck,
//                        EMNotifierEvent.Event.EventReadAck });
        EMClient.getInstance().chatManager().addMessageListener(this);
    }

    @Override
    protected void onStop() {
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(this);

        DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
                .getInstance();

        // 把此activity 从foreground activity 列表里移除
        sdkHelper.popActivity(this);
        //TTSPlayer.getInstense().stop();
        Kdxf_TTSPlayer.getInstense().stopTTs();
        Kdxf_TTSPlayer.getInstense().stop();
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (wakeLock.isHeld())
            wakeLock.release();
        //废弃
        if (VoicePlayClickListener.isPlaying
                && VoicePlayClickListener.currentPlayListener != null) {
            // 停止语音播放
            VoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }
        Kdxf_TTSPlayer.getInstense().stop();
        try {
            // 停止录音
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
                recordingContainer.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        if (getWindow()
                .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(
                        getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 加入到黑名单
     * 
     * @param username
     */
    private void addUserToBlacklist(final String username) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setMessage(getString(R.string.Is_moved_into_blacklist));
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().contactManager().addUserToBlackList(username,
                            false);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.Move_into_blacklist_success, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    R.string.Move_into_blacklist_failure, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 返回
     * 
     * @param view
     */
    public void back(View view) {
        EMClient.getInstance().chatManager().removeMessageListener(this);
        if (chatType == CHATTYPE_CHATROOM) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }
        finish();
    }

    /**
     * 覆盖手机返回键
     */
    @Override
    public void onBackPressed() {
        if (more.getVisibility() == View.VISIBLE) {
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
        } else {
            super.onBackPressed();
            if (chatType == CHATTYPE_CHATROOM) {
                EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
            }
        }
    }

    /**
     * listview滑动监听listener
     * 
     */
    private class ListScrollListener implements OnScrollListener {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
            case OnScrollListener.SCROLL_STATE_IDLE:
                /*
                 * if (view.getFirstVisiblePosition() == 0 && !isloading &&
                 * haveMoreData && conversation.getAllMessages().size() != 0) {
                 * isloading = true; loadmorePB.setVisibility(View.VISIBLE); //
                 * sdk初始化加载的聊天记录为20条，到顶时去db里获取更多 List<EMMessage> messages;
                 * EMMessage firstMsg = conversation.getAllMessages().get(0);
                 * try { // 获取更多messges，调用此方法的时候从db获取的messages //
                 * sdk会自动存入到此conversation中 if (chatType == CHATTYPE_SINGLE)
                 * messages =
                 * conversation.loadMoreMsgFromDB(firstMsg.getMsgId(),
                 * pagesize); else messages =
                 * conversation.loadMoreGroupMsgFromDB(firstMsg.getMsgId(),
                 * pagesize); } catch (Exception e1) {
                 * loadmorePB.setVisibility(View.GONE); return; } try {
                 * Thread.sleep(300); } catch (InterruptedException e) { } if
                 * (messages.size() != 0) { // 刷新ui if (messages.size() > 0) {
                 * adapter.refreshSeekTo(messages.size() - 1); }
                 * 
                 * if (messages.size() != pagesize) haveMoreData = false; } else
                 * { haveMoreData = false; }
                 * loadmorePB.setVisibility(View.GONE); isloading = false;
                 * 
                 * }
                 */
                break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        // 点击notification bar进入聊天页面，保证只有一个聊天页面
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    /**
     * 转发消息
     * 
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
        final EMMessage forward_msg = EMClient.getInstance().chatManager()
                .getMessage(forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
        case TXT:
            // 获取消息内容，发送消息
            String content = ((EMTextMessageBody) forward_msg.getBody())
                    .getMessage();
            String translate = null;
            textTask=content;
            try {
                translate = forward_msg.getStringAttribute("translate");
            } catch (HyphenateException e) {
                mPd.show();
                isVoice = false;
                if("chen".equals(transferType)){
                    ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_CHEN);
                }else{
                    ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
                }

                ZTTranslator.getTranslatorInstance().translate(mTranLisenter,content);
            }
            sendText(content, translate);
            break;
        case IMAGE:
            // 发送图片
            String filePath = ((EMImageMessageBody) forward_msg.getBody())
                    .getLocalUrl();
            if (filePath != null) {
                File file = new File(filePath);
                if (!file.exists()) {
                    // 不存在大图发送缩略图
                    filePath = ImageUtils.getThumbnailImagePath(filePath);
                }
                sendPicture(filePath);
            }
            break;
        default:
            break;
        }

        if (forward_msg.getChatType() == EMMessage.ChatType.ChatRoom) {
            EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
        }
    }

    /**
     * 监测群组解散或者被T事件
     * 
     */
    class GroupListener extends GroupRemoveListener {

        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            runOnUiThread(new Runnable() {
                String st13 = getResources().getString(R.string.you_are_group);

                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(ChatActivity.this, st13, Toast.LENGTH_SHORT).show();
                        if (GroupDetailsActivity.instance != null)
                            GroupDetailsActivity.instance.finish();
                        finish();
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(final String groupId, String groupName) {
            // 群组解散正好在此页面，提示群组被解散，并finish此页面
            runOnUiThread(new Runnable() {
                String st14 = getResources()
                        .getString(R.string.the_current_group);

                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(ChatActivity.this, st14, Toast.LENGTH_SHORT).show();
                        if (GroupDetailsActivity.instance != null)
                            GroupDetailsActivity.instance.finish();
                        finish();
                    }
                }
            });
        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {

        }

    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    public ListView getListView() {
        return listView;
    }


    /**
     * 紫冬翻译回调接口
     */
    private ZTTranslatorListener mTranLisenter = new ZTTranslatorListener() {
        @Override
        public void onResult(String text) {
            mPd.dismiss();
            if(isVoice)
                sendVoice(voiceurl, voicefilename, "100", false, textTask, text);
            else
                sendText(textTask, text);
        }

        @Override
        public void onError(int i) {
            if(mPd != null && mPd.isShowing()){
                mPd.dismiss();
            }
            Toast.makeText(ChatActivity.this, "翻译失败,请检查网络！", Toast.LENGTH_SHORT)
                    .show();
            Log.d(TAG, "翻译错误,错误码:" + i);
        }
    };

    /**
     * 语言种类选择
     */
   /* private void initBox() {
        // 筛选弹出框
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        mWindowView = layoutInflater.inflate(R.layout.custom_popup_window,
                null);
        mSelectList = (ListView) mWindowView
                .findViewById(R.id.lv_window_select);
        mPopupWindow = new MyPopupWindow(mWindowView,
                getResources()
                        .getDimensionPixelSize(R.dimen.pupup_window_width_mini),
                LayoutParams.WRAP_CONTENT, new OnDismiss() {
                    @Override
                    public void onDismiss() {
                        // 调节背景的亮度
                        CommonUtils.backgroundAlpha(ChatActivity.this, 1.0f);
                    }
                });
        ArrayList<HashMap<String, Object>> mListItem = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map1 = new HashMap<String, Object>();
        map1.put("one", "中");
        map1.put("two", "英");
        mListItem.add(map1);
        HashMap<String, Object> map2 = new HashMap<String, Object>();
        map2.put("one", "英");
        map2.put("two", "中");
        mListItem.add(map2);
        mPwAdapter = new MiniPopupWindowAdapter(this, mListItem, mPosition);
        mSelectList.setAdapter(mPwAdapter);

    }*/

   /* private void showWindow(View v) {
        // 使其聚集
        mPopupWindow.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 调节背景的亮度
        CommonUtils.backgroundAlpha(ChatActivity.this, 0.6f);
        // 计算popupWindow的偏移量
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int windowWidth = mPopupWindow.getWidth();
        int titleWidth = mLlChangeLanguageMini.getWidth();
        Log.i(TAG,
                "windowWidth" + windowWidth + "---->>>titleWidth" + titleWidth);
        int xoffInPixels = screenWidth / 2 - windowWidth / 2;
        ArrayList<HashMap<String, Object>> pwListItem1 = mPwAdapter
                .getListItem();
        for (int i = 0; i < pwListItem1.size(); i++) {
            pwListItem1.get(i).put("isSelect", false);
        }
        pwListItem1.get(LfyApplication.getInstance().getposition())
                .put("isSelect", true);
        mPopupWindow.showAsDropDown(v);
        mSelectList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                mPosition = position;
                if (position == 0) {
                    transferType = "chen";
                } else if (position == 1) {
                    transferType = "ench";
                }
                ArrayList<HashMap<String, Object>> pwListItem = mPwAdapter
                        .getListItem();

                for (int i = 0; i < pwListItem.size(); i++) {
                    pwListItem.get(i).put("isSelect", false);
                }
                pwListItem.get(position).put("isSelect", true);
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
                mTvChangeLanguageFirst.setText(mPwAdapter.getItem(position)
                        .get("itemTitle").toString());
                mTvChangeLanguageSecond.setText(mPwAdapter.getItem(position)
                        .get("itemTitleTwo").toString());
                LfyApplication.getInstance()
                        .writeChatTranslationKindsPreference(position);
            }
        });
    }*/
}
